package com.witdata.common.service.impl;

import com.mybatisflex.core.query.QueryWrapper;
import com.witdata.mysql.base.service.LogBaseService;
import com.witdata.common.domain.Status;
import com.witdata.common.domain.dto.LogDto;
import com.witdata.mysql.domain.entity.TLog;
import com.witdata.common.domain.vo.VisitTimesVo;
import com.witdata.common.exception.GlobalException;
import com.witdata.common.mapper.LogMapper;
import com.witdata.common.service.LogService;
import com.witdata.common.util.IdUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;

@Service
@RequiredArgsConstructor
public class LogServiceImpl implements LogService {
    private final LogBaseService logBaseService;

    @Override
    public void createLog(LogDto logDto) {
        TLog tLog = LogMapper.INSTANCE.toTLog(logDto);
        tLog.setId(IdUtils.createId());
        tLog.setCreated(LocalDateTime.now());
        boolean save = logBaseService.save(tLog);
        if (!save) throw new GlobalException(Status.SAVEERROR);
    }

    @Override
    public List<LogDto> getLogDtoList() {
        List<TLog> tLogList = logBaseService.list();
        return LogMapper.INSTANCE.toLogDtoList(tLogList);
    }

    @Override
    public VisitTimesVo getVisitTimestamp() {
        VisitTimesVo visitTimesVo = new VisitTimesVo();
        LocalDateTime localDateTime = LocalDateTime.now();
        for (int i = 6; i >= 0; i--) {
            LocalDateTime now = localDateTime.minusDays(i);
            LocalDate today = now.toLocalDate();
            LocalDateTime start = today.atStartOfDay();
            LocalDateTime end = today.atTime(23, 59, 59);
            QueryWrapper queryWrapper = new QueryWrapper();
            queryWrapper.ge("created", start);
            queryWrapper.le("created", end);
            long count = logBaseService.count(queryWrapper);
            visitTimesVo.getDate().add(today.toString());
            visitTimesVo.getCount().add(count);
        }
        return visitTimesVo;
    }

    @Override
    public Long getVisitCount() {
        LocalDateTime today = LocalDateTime.now();
        LocalDateTime startDay = today.withDayOfMonth(1);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.ge("created", startDay);
        queryWrapper.le("created", today);
        return logBaseService.count(queryWrapper);
    }
}
